#include "scene_game.h"
#include "scene_welcome.h"
#include "fstream"

using namespace cocos2d;

CCScene* scene_game::scene()
{
	CCScene * scene = NULL;
	scene = CCScene::create();
	scene_game *layer = scene_game::create();
	scene->addChild(layer);
	return scene;
}


bool scene_game::init()
{

	CCLayer::init();
	//	this->setTouchEnabled(true);
	CCSize size = CCDirector::sharedDirector()->getWinSize();
	CCSprite* pSprite = CCSprite::create("bg2.jpg");
	pSprite->setPosition(ccp(size.width / 2, size.height / 2));
	this->addChild(pSprite, 0);

	Audio::bg_play();

	star = new Star(this);
	label = new Label1(this);
	Audio::play_go();

	switch (rand() % 3)
	{
	case 0:CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic("gamebg1.mp3", true); break;
	case 1:CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic("gamebg0.mp3", true); break;
	case  2:CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic("boss1.mp3", true); break;
	default:
		break;
	}
	auto listener1 = EventListenerTouchOneByOne::create();
	listener1->setSwallowTouches(true);

	listener1->onTouchBegan = [=](Touch* touch, Event* event)
	{
		auto target = static_cast<Sprite*>(event->getCurrentTarget());

		Point locationInNode = target->convertToNodeSpace(touch->getLocation());
		Size s = target->getContentSize();
		Rect rect = Rect(0, 0, s.width, s.height);

		if (rect.containsPoint(locationInNode))
		{

			
			xy.x = locationInNode.x / 48;
			xy.y = locationInNode.y / 48-2;
			if ((xy.x >= 0 && xy.x < 10) && (xy.y < 10 && xy.y >= 0))
			if (star->Star_exit[xy.x][xy.y] != 100)
			{
				listener1->setSwallowTouches(false);
				star->will_search.push(xy);
				star->will_delete.push(xy);
				star->Search();
				int a = star->Delete();
				if (a != 0)
					label->Bonus(a);
				zz += a;
				label->setScore(zz);
				
				star->move_down();
				star->move_left();
				star->move_down();
				star->move_left();
				Audio::play_bonus(a);
				if (star->is_over() == true)
				{
					ofstream onfile("score.txt", ios::out);
					onfile << zz;
					onfile.close();
					this->removeAllChildren();

					star = new Star(this);
					label = new Label1(this);
				}
				listener1->setSwallowTouches(true);
			}

			




		//	log("sprite began... x = %f, y = %f", locationInNode.x, locationInNode.y);
			//target->setOpacity(100);
			return true;
		}
		return false;
	};

	_eventDispatcher->addEventListenerWithSceneGraphPriority(listener1, this);


	return true;

}
